package com.scujj.controller.impl;

import com.alibaba.fastjson.JSON;
import com.scujj.controller.ChatSocketController;
import com.scujj.pojo.ChatRecords;
import com.scujj.pojo.Message;
import com.scujj.service.ChatRecordsService;
import com.scujj.util.WsDyUtil;
import com.scujj.util.WsUtil;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint("/chatSocket")
@Component
public class ChatSocketControllerImpl implements ChatSocketController {
    private static final Map<Long, Session> sessionMap = new HashMap<>();
    public static ChatRecordsService chatRecordsService;
    public static StringRedisTemplate stringRedisTemplate;

    String idString;

    @SneakyThrows
    @Override
    @OnOpen
    public void onOpen(Session session) {
        String token = session.getRequestParameterMap().get("token").get(0);
        idString = stringRedisTemplate.opsForValue().get(token);
        if (idString == null) {
            System.out.println("用户未登录");
            session.close(new CloseReason(() -> -1, "用户未登录"));
            return;
        }
        sessionMap.put(Long.valueOf(idString), session);
        WsDyUtil wsDyUtil = new WsDyUtil(session);
        wsDyUtil.sendSuccess("连接成功");
    }

    @SneakyThrows
    @Override
    @OnMessage
    public void onMessage(Session session, String message) {
        Message messageObj = JSON.parseObject(message, Message.class);
        Long suid = Long.valueOf(idString);
        Long guid = messageObj.getGuid();
        Message.Type type = messageObj.getType();
        Object data = messageObj.getData();
        Session gsession = sessionMap.get(guid);
        ChatRecords chatRecords = new ChatRecords();
        switch (type) {
            case TEXT: {
                chatRecords.setSuid(suid).setGuid(guid).setType("text").setContent((String) data).setPublishTime(new Date());
                break;
            }
            case FILE: {
                break;
            }
        }
        if (chatRecordsService.save(chatRecords)) {
            WsUtil.sendJSON(session, chatRecords, "smessage");
            if (gsession != null) {
                WsUtil.sendJSON(gsession, chatRecords, "gmessage");
            }
        } else {
            WsUtil.sendErr(session, "网络错误", "smessage");
        }
    }

    @SneakyThrows
    @Override
    @OnClose
    public void onClose(Session session) {
        WsUtil.sendClose(session, "close");
    }

    @Override
    @OnError
    public void onError(Session session, Throwable error) {
        WsUtil.sendErr(session, "网络错误", "error");
    }
}
